<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminTenant\Action\Admin;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\User\Contract\UserContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Contract\AdminUserContract;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;
use MoChat\Plugin\TenantProduct\Contract\TenantProductSkuContract;

/**
 * 租户管理-列表.
 *
 * Class Index.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @Inject
     * @var TenantProductSkuContract
     */
    protected $tenantProductSkuService;

    /**
     * @Inject
     * @var AdminUserContract
     */
    protected $adminUserService;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @RequestMapping(path="/admin/tenant/index", methods="get")
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        $adminUser = user();
        // 接收参数
        $params = [
            'phone' => trim($this->request->input('phone', '')),
            'startTime' => $this->request->input('startTime', ''),
            'endTime' => $this->request->input('endTime', ''),
            'skuId' => (int) $this->request->input('skuId', 0),
            'userId' => $this->request->input('userId', ''),
            'page' => $this->request->input('page', 1),
            'perPage' => $this->request->input('perPage', '10000'),
        ];
        // 参数验证
        $this->validated($this->request->all());
        // 组织查询条件
        $where = [];
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        // 管理员/代理
        $creatorId = 0;
        if ($adminUser['isRoot'] === 0) {
            $creatorId = $adminUser['id'];
            $where['owner_id'] = $adminUser['id'];
        }
        // 租户名称/手机号
        if (! empty($params['phone'])) {
            $where[] = ["((`name` LIKE '%{$params['phone']}%') OR (`phone` LIKE '%{$params['phone']}%'))"];
        }
        // 注册时间
        if (! empty($params['startTime'])) {
            $where[] = ['created_at', '>=', $params['startTime']];
            $where[] = ['created_at', '<=', $params['endTime']];
        }
        // 套餐
        if (! empty($params['skuId'])) {
            $where['sku_id'] = $params['skuId'];
        }
        // 所属账户
        if (! empty($params['userId'])) {
            $creatorId = $params['userId'];
            $where['owner_id'] = $params['userId'];
        }
        // 查询数据
        $columns = ['id', 'name', 'status', 'max_employee', 'max_corp', 'expired_at', 'sku_id', 'root_id', 'owner_id', 'created_at'];
        $res['data'] = $this->tenantService->getTenantListSearch((int) $creatorId, $params['skuId'], $params['phone'], $params['startTime'], $params['endTime'], $columns);
        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];

        if (empty($res['data'])) {
            return $data;
        }
        // 处理分页数据
//        $data['page']['total'] = $res['total'];
//        $data['page']['totalPage'] = $res['last_page'];
        // 处理数据
        foreach ($res['data'] as &$item) {
            $user = $this->adminUserService->getAdminUserById($item['ownerId'], ['name']);
            $item['creatorName'] = ! empty($user) ? $user['name'] : '';
            $sku = $this->tenantProductSkuService->getTenantProductSkuByIdWithTrashed($item['skuId'], ['attributes']);
            $user = $this->userService->getUserById($item['rootId'], ['phone']);
            $item['phone'] = empty($user) ? '' : $user['phone'];
            if (! empty($sku)) {
                $attributes = $this->tenantProductSkuService->getTenantProductSkuValuesById(explode(',', $sku['attributes']));
                foreach ($attributes as $v) {
                    if ($v['attributeName'] === '套餐名称') {
                        $item['skuName'] = $v['attributeValue'];
                        break;
                    }
                }
            } else {
                $item['skuName'] = '';
            }
        }
        $data['list'] = $res['data'];
        return $data;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
